package com.rongxue.service.utils;

import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.Impl.CashInAndOutServiceImpl;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.ExceptionUtils;
import com.rongxue.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class RecordsUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecordsUtils.class);

    @Autowired
    private SProjectMapper projectMapper;
    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SInvestmentDetailMapper investmentDetailMapper;
    @Autowired
    private SUserRedenvelopeMapper userRedenvelopeMapper;//红包
    @Autowired
    private SUserInterestCouponMapper userInterestCouponMapper;
    @Autowired
    private SRechargeLogMapper rechargeLogMapper;
    @Autowired
    private SUserAccountMapper userAccountMapper;
    @Autowired
    private SAccountDetailMapper accountDetailMapper;
    @Autowired
    private SUserWalletRecordsMapper userWalletRecordsMapper;
    @Autowired
    private SUserMoneyRecordsMapper userMoneyRecordsMapper;
    @Autowired
    private SRepaymentDetailMapper repaymentDetailMapper;
    @Autowired
    private SUserDueDetailMapper userDueDetailMapper;
    @Autowired
    private SUserCashCouponMapper userCashCouponMapper;
    @Autowired
    private SInviterInvestmentRecordMapper inviterInvestmentRecordMapper;
    @Autowired
    private SExperienceMapper experienceMapper;
    @Autowired
    private SIntegralMapper sIntegralMapper;
    @Autowired
    private SUserRedenvelopeMapper sUserRedenvelopeMapper;

    //  保存充值或提现记录,不管成功还是失败
    public ObjectResult insertWalletRecords( Long userId, Integer type, BigDecimal transAmount,String refnumberId, String reMark, Integer deviceType,
                                             Integer status, Integer bankId) {

        Date date = new Date();
        SUserWalletRecords sUserWalletRecords = new SUserWalletRecords();
        try {
            sUserWalletRecords.setUser_id(userId);
            sUserWalletRecords.setRecharge_no(refnumberId);
            sUserWalletRecords.setPayType(1);
            sUserWalletRecords.setValue(transAmount);
            sUserWalletRecords.setType(type);
            sUserWalletRecords.setPayStatus(1);
            sUserWalletRecords.setStatus(status);
            sUserWalletRecords.setAdd_time(date);
            sUserWalletRecords.setModifyTime(date);
            sUserWalletRecords.setRemark(reMark);
            sUserWalletRecords.setDeviceType(deviceType);
            sUserWalletRecords.setUserBankId(bankId);
            userWalletRecordsMapper.insertSelective(sUserWalletRecords);

        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.build("0", "网络错误0x05,请稍后重试");
        }
        return null;
    }


    //  修改Wallet记录为成功
    public ObjectResult updateSuccessWalletRecords(SUserWalletRecords sUserWalletRecords, Long userId, Integer type, BigDecimal transAmount, Integer payStatus, String desc, String rechargeNo) {
        Date date = new Date();
        try {
//          修改钱包明细,设置成正常,已放款 type: 1收入 2支出 3借款 4还款 5现金券/ status: 1正常  2交易中  3待处理 / payStatus 1未支付  2已支付 3未放款 4已放款 5未还款 6已还款
            sUserWalletRecords.setStatus(1);
            sUserWalletRecords.setPayStatus(payStatus);
            sUserWalletRecords.setModifyTime(date);
            sUserWalletRecords.setRecharge_no(rechargeNo);
            sUserWalletRecords.setUser_id(userId);
            userWalletRecordsMapper.updateSelective(sUserWalletRecords);

        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.build("0000", "交易失败0x06,请联系客服处理");
        }
        return null;
    }


    //保存投标充值记录
    public ObjectResult insertRechargeLog(Long userId, Long projectId, String rechargeNo, BigDecimal realMoney, Integer rechargeLogStatus,String cardNo){
        SRechargeLog sRechargeLog = new SRechargeLog();
        Date date = new Date();
        sRechargeLog = new SRechargeLog();
        try {
            sRechargeLog.setUserId(userId);
            sRechargeLog.setProjectId(projectId);
            sRechargeLog.setRechargeNo(rechargeNo);
            sRechargeLog.setTradeNo(rechargeNo);//交易流水号
            sRechargeLog.setAmount(realMoney);
            sRechargeLog.setStatus(rechargeLogStatus);//1未支付,2已支付
            sRechargeLog.setAddTime(date);
            sRechargeLog.setAddUserId(userId);
            sRechargeLog.setModifyTime(date);
            sRechargeLog.setModifyUserId(userId);
            sRechargeLog.setCardNo(cardNo);rechargeLogMapper.insertSelective(sRechargeLog);

        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.build("0","网络错误0x05,请稍后重试");
        }
        return null;
    }

    //保存投资记录
    public ObjectResult insertInvestmentDetail(Long userId, Long projectId, String rechargeNo, Integer projectType, Integer rewardType, Integer rewardId,
                                               BigDecimal amoney, BigDecimal rewardValue, BigDecimal rateCoupon,String bankCardNo){

        SInvestmentDetail sInvestmentDetail = new SInvestmentDetail();
        Date date = new Date();
        SUserDueDetail sUserDueDetail = new SUserDueDetail();
        try {
            sInvestmentDetail.setUserId(userId);//01
            sInvestmentDetail.setProjectId(projectId);//02
            sInvestmentDetail.setInvTotal(amoney);//03
            sInvestmentDetail.setInvSucc(amoney);//04
            sInvestmentDetail.setAutoInv(1);//05
            sInvestmentDetail.setStatus(1);//06投标状态 1：未付款 2：投标成功 3：投标失败 4：已还款 5：还款中
            //sInvestmentDetail.setStatusNew(2);//07
            sInvestmentDetail.setRechargeNo(rechargeNo);//08
            sInvestmentDetail.setBowType(projectType);//09
            //使用账户直接进行投资
            //sInvestmentDetail.setCardNo(sRechargeLog.getCardNo());//10
            sInvestmentDetail.setAddTime(date);//11
            sInvestmentDetail.setAddUserId(userId);//12
            sInvestmentDetail.setModifyTime(date);//13
            sInvestmentDetail.setModifyUserId(userId);//14
            sInvestmentDetail.setRewardId(rewardId);
            sInvestmentDetail.setRewardType(rewardType);
            sInvestmentDetail.setRewardValue(rewardValue);
            sInvestmentDetail.setInterest(rateCoupon);
            sInvestmentDetail.setCardNo(bankCardNo);
            Long id = investmentDetailMapper.insertSelective(sInvestmentDetail);

        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.build("0", "网络错误0x05,请稍后重试");
        }

        return null;

    }


    //充值或提现成功添加记录
    public ObjectResult saveCashAndOutRecords(Long userId, BigDecimal transAmount, String desc, Integer type, String rechargeNo, Integer status){

        Date date = new Date();

        try {
            SUserMoneyRecords moneyRecords = new SUserMoneyRecords();
            //添加成功的userMoneyRecords记录
            moneyRecords.setUserId(userId);
            moneyRecords.setValue(transAmount);
            moneyRecords.setDescr(desc);
            moneyRecords.setType(108);
            moneyRecords.setStatus(status);
            moneyRecords.setAddTime(new Date());
            userMoneyRecordsMapper.insert(moneyRecords);

            //修改钱包记录为成功,只有充值需要二次修改,提现直接添加成功记录
            if (type == 1) {
                SUserWalletRecords sUserWalletRecords = new SUserWalletRecords();
                sUserWalletRecords.setPayStatus(Integer.valueOf(2));
                sUserWalletRecords.setModifyTime(date);
                sUserWalletRecords.setRecharge_no(rechargeNo);
                sUserWalletRecords.setUser_id(userId);
                sUserWalletRecords.setStatus(1);
                userWalletRecordsMapper.updateSelective(sUserWalletRecords);
            }
        } catch (Exception e) {
            ExceptionUtils.recordException(true, "用户"+userId+"充值或提现成功添加记录,操作数据库,发生异常","transAmount:"+transAmount, e);
            return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
        }

        return null;
    }

    public ObjectResult updateAccountAble(Long userId, BigDecimal transAmount){

        SUserAccount account = new SUserAccount();
        //修改钱包余额
        try {
            SUserAccount userAccount = userAccountMapper.selectUserAccountByUserId(userId);
            account.setId(userAccount.getId());
            account.setAccount_able(transAmount);
            account.setWalletTotle(transAmount);
            account.setModifyTime(new Date());
            account.setUserId(userId);
            userAccountMapper.updateUserAccountById(account);
        } catch (Exception e) {
            ExceptionUtils.recordException(true, "用户"+userId+"充值或提现成功添加记录,操作数据库,发生异常","transAmount:"+transAmount, e);
            return ObjectResult.build("0","服务器异常0x06,请联系客服处理");
        }

        return null;

    }

    //  保存返回码where trade_no = ?
    public void  saveCodeByTradeNo(String tradeNo, String code) {
        try {
            SUserWalletRecords sUserWalletRecords = new SUserWalletRecords();
            sUserWalletRecords.setPayCode(code);
            sUserWalletRecords.setRecharge_no(tradeNo);
            userWalletRecordsMapper.savePayCode(sUserWalletRecords);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    //添加成功投资记录,并更改账户余额
    public ObjectResult saveInvestmentRecordsAndUpdateAccount(Long userId, Long projectId, String rechargeNo, BigDecimal invTotal, Integer rewardId,
                                                              Integer rewardType, BigDecimal rewardValue, BigDecimal interest, Integer type, Integer bowType, String bankCardNo, Integer fromWallet) {

        Date date = new Date();
        try {
            //****修改充值记录s_recharge_log,设置状态为1未支付*********//
            SRechargeLog sRechargeLog = new SRechargeLog();
            sRechargeLog.setStatus(2);
            sRechargeLog.setModifyTime(date);
            sRechargeLog.setModifyUserId(userId);
            sRechargeLog.setRechargeNo(rechargeNo);
            rechargeLogMapper.updateSelective(sRechargeLog);

            //*******修改投资详情表 s_investment_detail 共 15 个字段,设置投标状态2成功********//
            SInvestmentDetail sInvestmentDetail = new SInvestmentDetail();
            sInvestmentDetail.setStatus(2);//投标状态 1：未付款 2：投标成功 3：投标失败 4：已还款 5：还款中
            sInvestmentDetail.setStatusNew(2);//07
            sInvestmentDetail.setModifyTime(date);//13
            sInvestmentDetail.setModifyUserId(userId);//14
            sInvestmentDetail.setRechargeNo(rechargeNo);
            sInvestmentDetail.setUserId(userId);
            investmentDetailMapper.updateSelective(sInvestmentDetail);

            //******************修改钱包明细s_user_wallet_records,设置成正常,已支付*********************//
            SUserWalletRecords sUserWalletRecords = new SUserWalletRecords();
            //type: 1收入 2支出 3借款/ status: 1正常  2交易中  3待处理 / payStatus 1未支付  2已支付 3未放款 4已放款
            sUserWalletRecords.setStatus(1);
            sUserWalletRecords.setPayStatus(2);
            sUserWalletRecords.setModifyTime(date);
            sUserWalletRecords.setRecharge_no(rechargeNo);
            sUserWalletRecords.setUser_id(userId);
            userWalletRecordsMapper.updateSelective(sUserWalletRecords);

            //************添加资金明细*************//
            SAccountDetail sAccountDetail = new SAccountDetail();
            sAccountDetail.setUserId(userId);
            //sAccountDetail.setAccountTotal(userAccount.getAccountTotal());
            //sAccountDetail.setAccountAble(userAccount.getAccountAble());
            sAccountDetail.setChangeAmount(invTotal);
            sAccountDetail.setType(1);
            sAccountDetail.setStatus(1);
            sAccountDetail.setRemark("钱包投资,投资编号:" + rechargeNo);
            sAccountDetail.setAddTime(date);
            sAccountDetail.setAddUserId(userId);
            sAccountDetail.setModifyTime(date);
            sAccountDetail.setModifyUserId(userId);
            sAccountDetail.setRewardId(rewardId);
            sAccountDetail.setRewardType(rewardType);
            sAccountDetail.setRewardValue(rewardValue);
            accountDetailMapper.insertSelective(sAccountDetail);

            //******************修改标的信息************//
            SProjectWithBLOBs project = projectMapper.selectByPrimaryKey(projectId);
            project.setAble(project.getAble().subtract(invTotal));
            if (project.getAble().doubleValue() > 0) {
                //投资进度
                BigDecimal percent = (project.getAmount().subtract(project.getAble())).divide(project.getAmount(), 10, BigDecimal.ROUND_HALF_EVEN).multiply(BigDecimal.valueOf(100));
                DecimalFormat df = new DecimalFormat("#.00");
                String bl = df.format(percent);
                project.setPercent(BigDecimal.valueOf(Double.valueOf(bl)));
            } else {
                BigDecimal percent = new BigDecimal("100");
                project.setAble(new BigDecimal("0"));
                project.setPercent(percent);
                project.setSoldoutTime(date);
                project.setStatus(3);

            }
            project.setModifyTime(date);
            projectMapper.updateByProjectId(project);
            //修改红包或者加息券的状态
            if (rewardType == 1) {
                SUserRedenvelope userRedenvelope = new SUserRedenvelope();
                userRedenvelope.setId(rewardId);
                userRedenvelope.setRechargeNo(rechargeNo);
                userRedenvelope.setProjectId(Integer.parseInt(project.getId()));
                userRedenvelope.setStatus(1);
                userRedenvelope.setUserId(userId.intValue());
                userRedenvelope.setModifyTime(date);
                userRedenvelopeMapper.updateByPrimaryKeySelective(userRedenvelope);

            } else if (rewardType == 2) {
                //修改加息券的信息
                SUserInterestCoupon userInterestCoupon = new SUserInterestCoupon();
                userInterestCoupon.setId(rewardId);
                userInterestCoupon.setProjectId(Integer.parseInt(project.getId()));
                userInterestCoupon.setStatus(1);
                userInterestCoupon.setRechargeNo(rechargeNo);
                userInterestCoupon.setUserId(userId.intValue());
                userInterestCoupon.setModifyTime(date);
                userInterestCouponMapper.updateByPrimaryKeySelective(userInterestCoupon);
            }

            //*************************投标明细***********************//
           /* SUserMoneyRecords sUserMoneyRecords = new SUserMoneyRecords();
            sUserMoneyRecords.setUserId(userId);
            sUserMoneyRecords.setValue(sRechargeLog.getAmount());
            sUserMoneyRecords.setDescr("钱包投资");
            sUserMoneyRecords.setType(108);
            sUserMoneyRecords.setStatus(2);
            sUserMoneyRecords.setDescr("用户投标");
            sUserMoneyRecords.setAddTime(new Date());
            userMoneyRecordsMapper.insertSelective(sUserMoneyRecords);*/
            // 添加待收明细 先查询标的还款计划
            //**  step-5 添加投资回报表 s_user_due_detail  共需要插入23个字段 *//
            SUserDueDetail sUserDueDetail;
            // 计算出日利息
            DecimalFormat df = new DecimalFormat("#.00");
            Calendar cal = Calendar.getInstance();
            BigDecimal totalDueInterest = BigDecimal.ZERO;
            BigDecimal dayInterest;

            SRepaymentDetailExample srexample = new SRepaymentDetailExample();
            SRepaymentDetailExample.Criteria srcriteria = srexample.createCriteria();
            srcriteria.andProjectIdEqualTo(Long.parseLong(project.getId()));
            srcriteria.andStatusEqualTo(1);
            List<SRepaymentDetail> rdList = repaymentDetailMapper.selectByExample(srexample);
            SRepaymentDetail srd = rdList.get(0);

            sUserDueDetail = new SUserDueDetail();
            sUserDueDetail.setUserId(userId);//01
            sUserDueDetail.setFromWallet(fromWallet);
            sUserDueDetail.setProject_id(Long.parseLong(project.getId()));//02
            sUserDueDetail.setRepayId(srd.getId());//03
            SInvestmentDetail investmentDetail = investmentDetailMapper.selectIdByRechargeNo(rechargeNo);
            sUserDueDetail.setInvestDetailId(investmentDetail.getId());//05
            //计息方式 1：T+0  2：T+1 3：T+2等,目前的countInterestType都是2: T+1
            if (project.getCountInterestType() == 2) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
            if (project.getCountInterestType() == 3) {
                cal.add(Calendar.DAY_OF_MONTH, 2);
            }
            sUserDueDetail.setStartTime(cal.getTime());//06
            //收益天数 待收益的日期-投标开始收益时间
            //int durationDay = DateUtil.getDaysBetweenToDate(project.getEnd_time(), sUserDueDetail.getStartTime()) + 1;
            //固定为标的天数
            int durationDay = project.getDuration();
            sUserDueDetail.setDurationDay(durationDay);//07
            //计算日利息
            //BigDecimal subsidy = project.getUserPlatformSubsidy();//平台补贴的利息
            dayInterest = interest.divide(BigDecimal.valueOf(365 * 100), 10, BigDecimal.ROUND_HALF_EVEN);
            //设置 利息，本金和本息
            sUserDueDetail.setDue_interest(BigDecimal.valueOf(Double.valueOf(df.format(dayInterest.multiply(BigDecimal.valueOf(sUserDueDetail.getDurationDay())).multiply(invTotal)))));//08
            sUserDueDetail.setDue_capital(invTotal);//09
            sUserDueDetail.setDueAmount(BigDecimal.valueOf(Double.valueOf(df.format(sUserDueDetail.getDue_capital().add(sUserDueDetail.getDue_interest())))));//10
            sUserDueDetail.setPeriod(srd.getPeriod());//11
            sUserDueDetail.setStatus(1);//投资中
            sUserDueDetail.setDueTime(srd.getRepaymentTime());//13
            sUserDueDetail.setBowType(project.getType());//14
            //目前是钱包支付，没有填银行卡号
            sUserDueDetail.setCardNo(bankCardNo);//15
            sUserDueDetail.setToWallet(1);//17
            sUserDueDetail.setAddTime(date);//18
            sUserDueDetail.setAddUserId(userId);//19
            sUserDueDetail.setModifyTime(date);//20
            sUserDueDetail.setModifyUserId(userId);//21
            sUserDueDetail.setInterestCoupon(rewardType == 3 ? rewardValue : new BigDecimal(0.00));//23
            userDueDetailMapper.insertSelective(sUserDueDetail);
            totalDueInterest = totalDueInterest.add(sUserDueDetail.getDue_interest());

            //**  step-6 第二次修改帐户表 s_user_account  共6个字段 *//
            SUserAccountExample example = new SUserAccountExample();
            SUserAccountExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            List<SUserAccount> userAccounts = userAccountMapper.selectByExample(example);
            SUserAccount userAccount2 = null;
            if (userAccounts.size() > 0) {
                userAccount2 = userAccounts.get(0);
            }
            SUserAccount atemp2 = new SUserAccount();
            atemp2.setId(userAccount2.getId());
            // 修改本金、利息、金额
            atemp2.setWaitCapital(invTotal.add(userAccount2.getWaitCapital()));//04待收总本金
            atemp2.setWait_interest(totalDueInterest.add(userAccount2.getWait_interest()));//05待收总利息
            atemp2.setWait_amount(atemp2.getWaitCapital().add(atemp2.getWait_interest()));//06待收总金额
            if (type == 2) {
                //只有余额投资,扣除余额
                atemp2.setAccount_able(userAccount2.getAccount_able().subtract(invTotal/*.subtract(rewardType == 1 ? rewardValue : new BigDecimal(0.00)))*/));
                atemp2.setWalletTotle(userAccount2.getWalletTotle().subtract(invTotal/*.subtract(rewardType == 1 ? rewardValue : new BigDecimal(0.00)))*/));//01
            }
            userAccountMapper.updateByPrimaryKeySelective(atemp2);
            //**************************添加资金明细 用户投标*********************//
            SAccountDetail sAccountDetail2 = new SAccountDetail();
            sAccountDetail2.setUserId(userId);
            sAccountDetail2.setAccountTotal(atemp2.getAccount_total());
            sAccountDetail2.setAccountAble(atemp2.getAccount_able());
            sAccountDetail2.setAccountFreeze(atemp2.getAccountFreeze());
            sAccountDetail2.setChangeAmount(sRechargeLog.getAmount());
            sAccountDetail2.setType(2);
            sAccountDetail2.setStatus(1);
            sAccountDetail2.setRemark("用户钱包投标，充值编号：" + sRechargeLog.getRechargeNo());
            sAccountDetail2.setAddTime(date);
            sAccountDetail2.setAddUserId(userId);
            sAccountDetail2.setModifyTime(date);
            sAccountDetail2.setModifyUserId(userId);
            accountDetailMapper.insertSelective(sAccountDetail2);


            //如果时新手标,只能投一次,修改用户为非新手
            SUser sUser = new SUser();
            sUser.setLevel(2);
            SUserExample userExample = new SUserExample();
            userExample.createCriteria().andIdEqualTo(userId);
            userMapper.updateByExampleSelective(sUser, userExample);

            userAccountMapper.updateByPrimaryKeySelective(atemp2);

            SUser user = userMapper.selectByPrimaryKey(userId);
//
//            //给邀请人发送加息券
//            addAwardType2Card(user, invTotal, rechargeNo);
//
//            //增加邀请人的投资记录
//            addInviterInvestmentRecord(sUserDueDetail);
//
//            //添加积分
            addScore(user, invTotal);

            if(project.getAble().compareTo(new BigDecimal(0))<=0){
                //土豪奖
                if (project.getTycoon_value()!=null&&project.getTycoon_value()>0){
                    SUserDueDetail userDueDetail = userDueDetailMapper.selectInvestmentMax(projectId.toString());
                    redenvelope(userDueDetail.getUserId().toString(),"土豪奖红包",new BigDecimal(project.getTycoon_value()),new BigDecimal(10000),30,15);
                }
                //收官奖
                if (project.getLast_valiu()!=null&&project.getLast_valiu()>0){
                    redenvelope(userId.toString(),"收官奖奖红包",new BigDecimal(project.getLast_valiu()),new BigDecimal(10000),30,15);
                }
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
            return ObjectResult.build("0", "网络错误0x06,请稍后重试");
        }
        return null;
    }

    /**
     * 增加加息劵给邀请人
     *
     * @param sUser   投资人
     */
    public int addAwardType2Card(SUser sUser, BigDecimal invTotal, String rechargeNo) {



        BigDecimal n5000 = new BigDecimal(5000);
        // 判断首次投资 ，金额大于5000 的情况
        if (invTotal.compareTo(n5000) >= 0 && sUser.getLevel() == 1
                && sUser.getAddUserId() != null && sUser.getAddUserId() != 0L) {
            try {
                SUserInterestCoupon record = new SUserInterestCoupon();
                record.setAddTime(new Date());
                record.setAddUserId(Integer.valueOf(sUser.getAddUserId().toString()));
                //加息劵ID
                record.setCouponId(Integer.valueOf(DateUtil.formatLongDateTime().substring(2,8)+ RandomUtil.getSMSCODE()));
                record.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis() / 1000)));
                //设置有效天数30天
                record.setExpireTime(DateUtil.addDateDay(new Date(), 30));
                //FIXME 这里id设置有问题，不能每次都是0，否则加息券没法使用
                record.setInterestRate(new BigDecimal(1.2));
                // 0 表示未删除
                record.setIsDelete((byte) 0);
                //0:未读；1：已读
                record.setIsRead((byte) 0);
                //最小投资期限
                record.setMinDue(0);
                //最小投资金额
                record.setMinInvest(new BigDecimal(0));
                record.setModifyTime(new Date());
                record.setModifyUserId(Integer.valueOf(String.valueOf(sUser.getId())));
                //record.setProjectId(Integer.valueOf(xmlBean.getProject_id()));
                record.setProjectId(Integer.valueOf(0));
                record.setRechargeNo(rechargeNo);
                //0个人，1所有人
                record.setScope(0);
                record.setSource(sUser.getId().toString());
                //0初始，1已使用，2过期
                record.setStatus(0);
                String tel = sUser.getMobile();
                tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                record.setSubtitle("来自好友"+tel);
                record.setTitle("邀请好友加息劵");
                record.setUserId(Integer.valueOf(sUser.getAddUserId().toString()));
                userInterestCouponMapper.insertSelective(record);
            } catch (Exception e) {

                ExceptionUtils.recordException(true, "用户"+sUser.getMobile()+",增加加息劵给邀请人,操作数据库,发生异常", "流水号:"+rechargeNo, e);
            }
        }

        return -1;
    }


    /**
     * 增加邀请人的投资记录
     *
     */
    private void addInviterInvestmentRecord(SUserDueDetail sUserDueDetail){
        Long userId = sUserDueDetail.getUserId();
        SUser sUser =userMapper.selectUserInfoById(userId);

        BigDecimal dueCapital = sUserDueDetail.getDue_capital(); // 投资总金额
        BigDecimal n5000 = new BigDecimal(5000);
        //if(dueCapital.compareTo(n5000)>=0 && sUser.getLevel()==1){
        if(sUser.getAddUserId()!=null && sUser.getAddUserId()!=0){

            try {
                SInviterInvestmentRecord record = new SInviterInvestmentRecord();
                record.setAddTime(DateUtil.formatDateTime());
                record.setId(0);
                record.setInvestorAmount(dueCapital);
                record.setInviterId(Integer.valueOf(String.valueOf(sUser.getAddUserId())));
                record.setInvestorId(Integer.valueOf(String.valueOf(userId)));
                record.setInvestorInterest(sUserDueDetail.getDue_interest());
                record.setInviterInterest(sUserDueDetail.getDue_interest().multiply(BigDecimal.valueOf(0.1)));
                record.setModifyTime(DateUtil.formatDateTime());
                record.setProjectId(Integer.valueOf(sUserDueDetail.getProject_id().toString()));
                SProject sProject = projectMapper.selectProjectById(String.valueOf(sUserDueDetail.getProject_id()));
                if(sProject!=null && StringUtils.isNotEmpty(sProject.getTitle())){
                    record.setProjectTitle(sProject.getTitle());
                }else{
                    record.setProjectTitle("");
                }
                record.setStatus((byte)1);
                record.setUserDueDetailId(Integer.valueOf(sUserDueDetail.getId()+""));
                inviterInvestmentRecordMapper.insert(record);
            } catch (Exception e) {

                ExceptionUtils.recordException(true, "用户"+sUser.getMobile()+",增加邀请人的投资记录,操作数据库,发生异常", "用户id"+userId+",projectId:"+sUserDueDetail.getPeriod(), e);
            }
        }

    }


    /**
     * 加积分
     */
    private int addScore(SUser sUser, BigDecimal invTotal) {
        try {
            BigDecimal n100 = new BigDecimal(100);
            int integral = invTotal.divide(n100).intValue();

            if (sUser.getIntegral() != null) {
                sUser.setIntegral(sUser.getIntegral() + integral);
            } else {
                sUser.setIntegral(integral);
            }
            //置为非新手
            if (sUser.getLevel() == 1) {
                sUser.setLevel(2);
            }
            SUserExample example = new SUserExample();
            example.createCriteria().andIdEqualTo(sUser.getId());
            userMapper.updateByExampleSelective(sUser, example);

            //添加积分记录
            Map<String,Object> map = new HashMap<>();
            map.put("userId",sUser.getId());
            map.put("type",2);
            map.put("integral",integral);
            sIntegralMapper.insertIntegralByMap(map);
        } catch (Exception e) {

            ExceptionUtils.recordException(true, "用户"+sUser.getMobile()+",增加积分,操作数据库,发生异常", "用户id"+sUser.getId()+",integral:"+sUser.getIntegral(), e);

        }

        return -1;
    }

    //发红包
    public void redenvelope(String userId,String title,BigDecimal amount,BigDecimal minInverst,Integer minDue,Integer day){
        try {
            SUserRedenvelope sUserRedenvelope = new SUserRedenvelope();
            sUserRedenvelope.setTitle(title);
            sUserRedenvelope.setContent(title);
            sUserRedenvelope.setUserId(Integer.parseInt(userId));
            sUserRedenvelope.setAmount(amount);
            sUserRedenvelope.setCreateTime(new Date());
            sUserRedenvelope.setMinInvest(minInverst);
            sUserRedenvelope.setMinDue(minDue);
            sUserRedenvelope.setExpireTime(DateUtil.addDateDay(new Date(), day));
            sUserRedenvelope.setStatus(0);
            sUserRedenvelopeMapper.insertSelective(sUserRedenvelope);
        }catch (Exception e){
            ExceptionUtils.recordException(true, "发红包,操作数据库,发生异常", "用户id:"+userId, e);
        }
    }

}
